//
//  YLChoiceAdressViewController.m
//  YLFinanceService
//
//  Created by she1323 on 2017/9/8.
//  Copyright © 2017年 she1323. All rights reserved.
//  选择地址

#import "YLChoiceAdressViewController.h"
#import <Masonry.h>
#import "YLAdressWhiteTableViewCell.h"
#import "YLGlobeHeader.h"
#import "YLAddAdressHeader.h"
#import "YLEditAdressViewController.h"
#import "YLAdressManagerViewController.h"
#import "YLAdressManagerViewModel.h"
#import "YLMyAdressModel.h"
#import <RACTuple.h>
@interface YLChoiceAdressViewController ()<YLAdressManagerViewControllerDelegate,YLEditAddressViewControllerDelegate>

@property (nonatomic, strong) YLAdressManagerViewModel *viewModel;

@property (nonatomic, assign) NSInteger selectedIndex;

@end

@implementation YLChoiceAdressViewController

- (YLAdressManagerViewModel *)viewModel
{
    if (!_viewModel) {
        _viewModel = [[YLAdressManagerViewModel alloc] init];
    }
    return _viewModel;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    _selectedIndex = 0;
    self.title = @"选择收货地址";
    
    
    __weak typeof(self) weakSelf = self;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.bottom.left.mas_equalTo(weakSelf.view);
    }];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([YLAdressWhiteTableViewCell class]) bundle:nil] forCellReuseIdentifier:[YLAdressWhiteTableViewCell cellID]];
    YLAddAdressHeader *header = [[YLAddAdressHeader alloc] initWithFrame:CGRectMake(0, 0, YLScreenW, 44)];
    
    [header.tapSignal subscribeNext:^(id  _Nullable x) {
        YLEditAdressViewController *edit = [[YLEditAdressViewController alloc] init];
        edit.title = @"新增收货地址";
        edit.delegate = self;
        [weakSelf.navigationController pushViewController:edit animated:YES];
    }];
    
    self.tableView.tableHeaderView = header;
   
    [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
    
    UIButton *managerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [managerButton setTitle:@"管理" forState:UIControlStateNormal];
    managerButton.titleLabel.font = [UIFont systemFontOfSize:13.0f];
    managerButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [managerButton setTitleColor:YLColor(94, 96, 107) forState:UIControlStateNormal];
    [managerButton addTarget:self action:@selector(toAdressManager) forControlEvents:UIControlEventTouchUpInside];
    managerButton.bounds = CGRectMake(0, 0, 70, 30);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:managerButton];
    
    [[self.viewModel.requestCommand execute:nil] subscribeNext:^(id  _Nullable x) {
        [weakSelf.tableView reloadData];
        for (NSInteger i = 0; i < weakSelf.viewModel.models.count; i ++) {
            YLMyAdressModel *model = weakSelf.viewModel.models[i];
            weakSelf.selectedIndex = i;
            if ([model.receiveAddressId isEqualToString:weakSelf.model.receiveAddressId]) {
                [weakSelf.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:i] animated:NO scrollPosition:UITableViewScrollPositionNone];
               // [self.tableView reloadData];
                return ;
            }
        }
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:@"YLEditAdressNoti" object:nil];
}

- (void)loadData
{
//    __weak typeof(self) weakSelf = self;
//    [[self.viewModel.requestCommand execute:nil] subscribeNext:^(id  _Nullable x) {
//        [weakSelf.tableView reloadData];
//    }];
}


- (void)toAdressManager
{
    if (!self.viewModel.models) {
        return;
    }
    
    YLAdressManagerViewController *address = [[YLAdressManagerViewController alloc] init];
    address.models = self.viewModel.models;
    address.delegate = self;
    [self.navigationController pushViewController:address animated:YES];
    __weak typeof(self) weakSelf = self;
    
    [[address.models rac_signalForSelector:@selector(removeObjectAtIndex:)] subscribeNext:^(RACTuple * _Nullable x) {
        if ([x.first integerValue] == weakSelf.selectedIndex) {
            if (weakSelf.viewModel.models.count > 0) {
               [weakSelf.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
                _selectedIndex = 0;
                [weakSelf setUpSelectedModelWithIndex:0];
            }
        }
    }];
}

- (void)addressManagerViewController:(YLAdressManagerViewController *)controller reloadAddresses:(NSArray *)models
{
    self.viewModel.models = [NSMutableArray arrayWithArray:models];
    [self.tableView reloadData];
}

- (void)edidAddressViewController:(YLEditAdressViewController *)controller addAddress:(YLMyAdressModel *)model
{
    [self.viewModel.models addObject:model];
    [self.tableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.viewModel.models.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YLAdressWhiteTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[YLAdressWhiteTableViewCell cellID]];
    cell.model = self.viewModel.models[indexPath.section];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self setUpSelectedModelWithIndex:indexPath.section];
    
    [self.navigationController popViewControllerAnimated:YES];
}



- (void)setUpSelectedModelWithIndex:(NSInteger)index
{
    
    YLMyAdressModel *model = self.viewModel.models[index];
    
    _model.receiveAddressId = model.receiveAddressId;
    _model.province = model.province;
    _model.city = model.city;
    _model.area = model.area;
    _model.receiveAddress = model.receiveAddress;
    _model.receiveName = model.receiveName;
    _model.receiveTel = model.receiveTel;
    _model.adress = model.adress;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.tableView reloadData];
    
    if (self.viewModel.models.count > 0) {
        [self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:_selectedIndex] animated:NO scrollPosition:UITableViewScrollPositionNone];
        [self setUpSelectedModelWithIndex:_selectedIndex];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
